package com.situ.crm.controller;

import com.situ.crm.util.Result;
import com.situ.crm.pojo.entity.User;
import com.situ.crm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ApiIgnore
@RequestMapping("/user")
@Controller
// @RestController = @Controller + 所有方法@ResponseBody
public class UserController {
	@Autowired
	private IUserService userService;

	@RequestMapping("/getUserPage")
	public String getUserPage() {
		return "/user/user_list";
	}

	@RequestMapping("/selectByPage")
	@ResponseBody
	public Result selectByPage(Integer page, Integer limit, User user, Date time) {
		System.out.println(time);
		Result result = userService.selectByPage(page, limit, user);
		return  result;
	}

	@RequestMapping("/deleteById")
	@ResponseBody
	public Result deleteById(Integer id) {
		boolean isSuccess = userService.deleteById(id);
		if (isSuccess) {
			return Result.success("删除成功");
		} else {
			return  Result.error("删除失败");
		}
	}

	@RequestMapping("/deleteAll")
	@ResponseBody
	public Result deleteAll(String ids) {
		boolean isSuccess =  userService.deleteAll(ids);
		if (isSuccess) {
			return Result.success("删除成功");
		} else {
			return  Result.error("删除失败");
		}
	}

	@RequestMapping("/getAddPage")
	public String getAddPage() {
		return "/user/user_add";
	}

	// BindingResult result一定要放在加了@Valid User user的后面，否则会报400错误
	// @RequestMapping("/add")
	@PostMapping("/add")
	@ResponseBody
	public Result add(@Valid User user, BindingResult result, String roles) {
		System.out.println(user);
		System.out.println(roles);

//		if (StringUtils.isEmpty(user.getName())) {
//			return Result.error("用户名不能为空");
//		}

		// 判断BindingResult是否保存错误的验证信息，如果有，则直接return
		if (result.hasErrors()) {
			Map<String, String> errorMap = getErrors(result);
			return Result.error(errorMap);
		}


		boolean isSuccess = userService.add(user, roles);
		if (isSuccess) {
			return Result.success("添加成功");
		} else {
			return Result.error("添加失败");
		}
	}

	private Map<String, String> getErrors(BindingResult result) {
		Map<String, String> map = new HashMap<>();
		List<FieldError> errorList = result.getFieldErrors();
		for (FieldError error : errorList) {
			// 发生验证错误所对应的某一个属性
			String errorField = error.getField();
			// 验证错误的信息
			String errorMsg = error.getDefaultMessage();
			map.put(errorField, errorMsg);
		}
		return map;
	}
	
	@RequestMapping("/update")
	@ResponseBody
	public Result update(User user, String roles) {
		System.out.println(user);
		System.out.println(roles);
		boolean isSuccess = userService.update(user, roles);
		if (isSuccess) {
			return Result.success("更新成功");
		} else {
			return  Result.error("更新失败");
		}
	}
	


	@RequestMapping("/getUpdatePage")
	public String getUpdatePage() {
		return "/user/user_update";
	}

	// @RequestMapping(value = "/selectUserAndRoles", method = RequestMethod.GET)
	@GetMapping("/selectUserAndRoles")
	@ResponseBody
	public Result selectUserAndRoles(Integer userId) {
		return userService.selectUserAndRoles(userId);
	}

	// 如果不加method = RequestMethod.POST，这个方法默认所有的请求GET/POST/PUT/DELETE都可以处理
	// 如果限定指定处理POST，而请求的是GET请求，就会报下面的错误
	// There was an unexpected error (type=Method Not Allowed, status=405).
	// Request method 'GET' not supported

	// @RequestMapping(value = "/login", method = RequestMethod.POST)
	@PostMapping("/login")
	@ResponseBody
	public Result login(String name, String password, HttpSession session) {
		// 有些人使用类似PostMan Talend API 这些工具可以绕过前台正则表达式的验证
		// 用户就有可能提交一些非法或者有害的信息，应该在后台再进行一次验证
		//  return str == null || "".equals(str);
		// TODO : 用户名4-8位
		if (StringUtils.isEmpty(name)) {
			return Result.error("用户名不能为空");
		}
		// TODO :  6位字母数字下划线
		if (StringUtils.isEmpty(password)) {
			return Result.error("密码不能为空");
		}

		return userService.login(name, password, session);
	}
	
	@RequestMapping("/getLoginPage")
	public String getLoginPage() {
		return "/user/login";
	}


}


